<template>
  <div class="common-container">
    <div class="header">
      <div class="header_left">
        <el-input
          placeholder="请输入消控室名称"
          v-model="searchForm.name"
          style="width: 260px; margin: 0 15px"
          size="small"
          maxlength="20"
          clearable
          @clear="clearName"
          class="el_input"
        >
          <el-button
            slot="append"
            :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'"
            @click="searchClick"
          >
          </el-button>
        </el-input>

        <el-popover
          placement="bottom"
          width="460"
          trigger="click"
          popper-class="popover"
          size="small"
          v-model="showPopover"
        >
          <div>
            <el-form
              label-width="70px"
              style="margin: 20px 0"
              class="popover_from"
            >
              <el-form-item
                size="small"
                label="组织机构"
                v-if="
                  user.roleName === 'TENANT_ADMIN' ||
                  user.roleName === 'ORG_ADMIN'
                "
              >
                <TreeSearch
                  style="width: 360px; margin-left: 15px"
                  @changeOrgId="changeOrgId"
                  ref="refTreeSearch"
                >
                </TreeSearch>
              </el-form-item>
              <el-form-item size="small" label="联网单位">
                <el-select
                  size="small"
                  style="width: 360px; margin-left: 15px"
                  clearable
                  v-model="selectedValue"
                  placeholder="请选择联网单位"
                  filterable
                  remote
                  @clear="handleClear"
                >
                  <el-option
                    v-for="item in orgList"
                    :label="item.orgName"
                    :value="item.id"
                    :key="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div class="footer" style="text-align: right">
              <el-button size="small" @click="resetClick" class="cancel-button"
                >重 置</el-button
              >
              <el-button size="small" class="confirm-button" @click="onSearch"
                >确 定</el-button
              >
            </div>
          </div>
          <el-button
            size="small"
            slot="reference"
            :class="hasSearch ? 'elhasSearch elhasSearch2' : 'elhasSearch2'"
          >
            高级搜索<i
              class="el-icon-search"
              style="margin-left: 5px; font-size: 12px"
            ></i
          ></el-button>
        </el-popover>
      </div>
      <div class="header_right">
        <el-button
          class="el_button"
          size="small"
          type="primary"
          icon="el-icon-plus"
          style="margin-left: 15px"
          @click="onAdd"
          v-permission="{ action: 'fireControl:add' }"
        >
          新增
        </el-button>
        <el-dropdown
          @command="onDropdown"
          v-permission="{ action: 'fireControl:batch:delete' }"
        >
          <el-button size="small" style="margin-left: 15px">
            批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="del">批量删除</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="content">
      <el-table
        :data="dataList"
        ref="refTable"
        class="table"
        :header-cell-style="headerStyle"
        row-key="id"
        @selection-change="batchSelect"
      >
        <el-table-column
          align="center"
          type="selection"
          :reserve-selection="true"
          width="60"
        ></el-table-column>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="80"
          height="30"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="name"
          label="消控室名称"
          min-width="200"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          prop="address"
          label="消控室地址"
          min-width="200"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          prop="orgName"
          label="联网单位"
          min-width="200"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          prop="userCount"
          label="消控室值班人员"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-popover
              placement="bottom"
              popper-class="popover"
              trigger="click"
            >
              <div
                v-for="item in scope.row.fcrDutyUserRelatedVOS"
                :key="item.userId"
              >
                <div style="margin: 8px 0">
                  <span style="margin-right: 10px">{{ item.mobile }}</span
                  ><span>{{ item.userName }}</span>
                </div>
              </div>
              <span slot="reference" class="user-count">{{
                scope.row.userCount
              }}</span>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="telephone"
          label="消控室电话"
          min-width="200"
          show-overflow-tooltip
        ></el-table-column>
        <!-- <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          min-width="140"
          show-overflow-tooltip
        ></el-table-column> -->
        <el-table-column align="center" label="操作" min-width="140">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="消控室大屏"
              placement="bottom"
              v-if="scope.row.isExsitHost"
            >
              <i
                @click="onFireControlDatav(scope.row)"
                class="iconfont konngzhidaping tableBtnIcon"
              ></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="bottom"
              v-permission="{ action: 'fireControl:edit' }"
            >
              <i
                @click="onEdit(scope.row)"
                class="iconfont tianxie tableBtnIcon"
              ></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="bottom"
              v-permission="{ action: 'fireControl:delete' }"
            >
              <i
                @click="onDel(scope.row)"
                class="iconfont shanchu tableBtnIcon"
              ></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page"
        :limit.sync="limit"
        :pageSizes="[10, 20, 30, 50]"
        @pagination="getDataList"
        class="pagination"
      />
    </div>
    <Add
      ref="refAdd"
      :itemInfo="itemInfo"
      :getLocationInfo="getLocationInfo"
      :getAddressflag="getAddressflag"
      @updateDataList="updateDataList"
    ></Add>
  </div>
</template>

<script>
import {
  reqFireControlRoomPage,
  reqFireControlRoomDel,
  reqFireControlRoomBatchDel,
  reqOrgList,
} from "@api/api.js";
import Pagination from "@components/Pagination.vue";
import tableStyleMixin from "@mixin/table-style";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";
import TreeSearch from "@components/TreeSearch.vue";
import Add from "./components/Add.vue";
import getAddress from "@/views/org/components/mixins/getAddress";

export default {
  name: "task",
  components: { Pagination, TreeSearch, Add },
  mixins: [tableStyleMixin, loadMore, getAddress],
  data() {
    return {
      searchForm: {
        name: "",
        orgId: "",
      },
      loadingSearch: false,
      dataList: [],
      limit: 10,
      page: 1,
      total: 0,

      itemInfo: {}, //一条记录信息

      projectList: [], //组织机构
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      loading: false,

      batchDataList: [], //

      getAddressflag: false, //地图选点
      getLocationInfo: {
        getLat: "",
        getLng: "",
        getAdd: "",
        province: "",
        city: "",
        area: "",
        provinceCityAreaValue: "",
      },
      selectedValue: "",
      orgList: [],
      hasSearch: false,
      showPopover: false,
    };
  },
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  async created() {},
  mounted() {
    // if (
    //   this.user.roleName == "ORG_ADMIN" ||
    //   this.user.roleName == "INSTERALL_USER"
    // ) {
    //   // 组织||装维
    //   this.searchForm.orgId = this.spacesManage.organizationInfo.orgId;
    //   // this.getInitDataList();
    // } else {
    //   // this.getInitDataList();
    // }
    if (
      this.user.roleName == "INSTERALL_USER" ||
      this.user.roleName == "UNIT_ADMIN"
    ) {
      this.getOrgList();
    }
    this.getInitDataList();
  },
  methods: {
    // 搜索
    async onSearch() {
      this.page = 1;
      this.limit = 10;
      this.showPopover = false;
      this.getDataList();
    },
    // 高级搜索重置
    async resetClick() {
      this.searchForm.orgId = "";
      this.selectedValue = "";
      this.page = 1;
      this.limit = 10;
      await this.getDataList();
      if (this.$refs.refTreeSearch) {
        this.$refs.refTreeSearch.onclose();
      }
      if (
        this.user.roleName != "INSTERALL_USER" &&
        this.user.roleName != "UNIT_ADMIN"
      ) {
        this.orgList = [];
      }
    },
    clearName() {
      this.getInitDataList();
    },
    async searchClick() {
      this.loadingSearch = true;
      await this.getInitDataList();
      this.loadingSearch = false;
    },
    // 选择组织机构
    changeOrgId(instanceId) {
      this.searchForm.orgId = instanceId.id;
      this.handleClear();
    },
    // 清空
    handleClear() {
      this.selectedValue = "";
      this.orgName = "";
      this.orgList = [];
      this.getOrgList();
    },
    // 远程搜索
    // async remoteMethod(query) {
    //   this.selectedValue = query //保留输入的值
    //   this.orgName = query;
    //   this.orgList = []
    //   this.getOrgList()
    // },
    // 请求单位列表
    async getOrgList() {
      let { tenantId, userId, roleName } = this.user;
      const res = await reqOrgList({
        tenantId,
        userId,
        roleName,
        orgName: this.orgName,
        parentId: this.searchForm.orgId,
        type: "4",
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.orgList = res.data.rows;
    },
    // 获取组织机构列表
    // async getOrgList() {
    //   var res = await reqOrgList({
    //     userId: this.user.userId,
    //     roleName: this.user.roleName,
    //     tenantId: this.user.tenantId,
    //   });
    //   if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
    //   this.sysInstanceTotalPages = res.data.total;
    // },

    // 获取列表
    async getDataList() {
      const res = await reqFireControlRoomPage(this.page, this.limit, {
        tenantId: this.user.tenantId,
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId:
          this.selectedValue == "" ? this.searchForm.orgId : this.selectedValue, //机构||单位
        name: this.searchForm.name,
      });

      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.hasSearch =
        this.searchForm.orgId || this.selectedValue ? true : false;
      let { rows, total } = res.data;
      if (rows.length) {
        rows.forEach((item) => {
          if (item.fcrDeviceRelateds.length) {
            for (
              let index = 0;
              index < item.fcrDeviceRelateds.length;
              index++
            ) {
              const element = item.fcrDeviceRelateds[index];
              if (
                element.deviceType ===
                  "UserTransferDevice" ||
                element.deviceType ===
                  "FireAlarmController"
              ) {
                item.isExsitHost = true;
                break;
              } else {
                item.isExsitHost = false;
              }
            }
          }
        });
      }
      this.dataList = rows;
      this.total = total;
      console.log(this.dataList, "this.dataList");
    },
    getInitDataList() {
      this.page = 1;
      this.limit = 10;
      this.getDataList();
    },

    // 新增
    onAdd() {
      this.itemInfo = {};
      this.$refs.refAdd.dialogVisible = true;
    },
    // 消控室大屏
    onFireControlDatav(row) {
      this.$router.replace({
        path: "/fire/controlRoom/datav",
        query: JSON.parse(JSON.stringify(row)),
      });
    },
    onEdit(row) {
      this.itemInfo = JSON.parse(JSON.stringify(row));
      this.$refs.refAdd.dialogVisible = true;
    },

    updateDataList() {
      this.getInitDataList();
    },

    // 删除
    async onDel(row) {
      const result = await this.$confirm(
        `此操作将永久删除消控室：${row.name}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (result !== "confirm") return;
      const res = await reqFireControlRoomDel(row.id);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("已删除");
      this.getInitDataList();
    },

    // 批量删除
    async deleteFoo() {
      const { batchDataList } = this;
      const result = await this.$confirm(
        `此操作将永久删除勾选的${batchDataList.length}个消控室, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (result !== "confirm") return;

      const ids = batchDataList.map((item) => item.id);
      const res = await reqFireControlRoomBatchDel(ids);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);

      this.$refs.refTable.clearSelection();
      this.$modal.notifySuccess("已删除");
      this.getInitDataList();
    },

    // 点击复选框触发，可跨分页选择
    batchSelect(arr) {
      this.batchDataList = arr;
    },

    async onDropdown(e) {
      if (this.batchDataList.length <= 0) {
        this.$modal.notifyWarning("请先勾选消控室");
        return;
      }
      switch (e) {
        case "del":
          this.deleteFoo();
          break;
      }
    },
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");
@import url("~@views/style/tree.less"); //左侧组织机构样式

::v-deep .el_button.el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 9999;
  // background: red;
  // opacity: 0.5;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束

::v-deep .el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}

.user-count {
  cursor: pointer;
  color: #7367f0;

  &:hover {
    text-decoration: underline;
  }
}

// 高级搜索
::v-deep .el-button--primary {
  background-color: #7367f0;
  border: 1px solid #7367f0;
  color: #fff;
}

::v-deep .el-form-item__label {
  color: @primaryThemeTxtColor2;
  padding: 0px;
}
::v-deep .el-input__inner {
  color: var(--primaryContentTxt, #f1f1f1) !important;
}

.dropdown {
  background: #7367f0;
  color: #fff;
  border: none;
}

::v-deep .el-button--small {
  border: none;
}
// 高级搜索----------
</style>
